package com.example.distillapplication.ui.activity;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.distillapplication.R;
import com.example.distillapplication.hardware.SerialManager;
import com.example.distillapplication.hardware.protcal.Protocol;
import com.example.distillapplication.ui.activity.base.BaseActivity;
import com.example.distillapplication.databinding.ActivityMainBinding;
import com.example.distillapplication.ui.fragment.set.ISetTimeAndSteamVolume;
import com.example.distillapplication.hardware.protcal.LogString;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity implements ISetTimeAndSteamVolume {
    ActivityMainBinding activityMainBinding;
    Handler timeHandler;
    Thread recieveThread;
    Handler sendHandler, steamAndTempHandler, waterLevelHandler;
    Timer sendTimer, steamAndTempTimer, waterLevelTimer;
    TimerTask sendTimerTask, steamAndTempTimerTask, waterLevelTimerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);


        NavController controller = Navigation.findNavController(this, R.id.fragment);
        AppBarConfiguration configuration = new AppBarConfiguration.Builder(controller.getGraph()).build();
        //NavigationUI.setupActionBarWithNavController(this, controller, configuration);
        NavigationUI.setupWithNavController(activityMainBinding.bottom, controller);


        timeHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1){
                    if(mInstrumentStateViewModel.targetTime.getValue() > 0){
                        int temp = mInstrumentStateViewModel.targetTime.getValue();
                        temp--;
                        mInstrumentStateViewModel.targetTime.postValue(temp);
                        timeHandler.sendEmptyMessageDelayed(1, 1000);
                    }else{
                        mSerialMessageViewModel.onDistillFlag.postValue(0);
                        mSharedViewModel.setOperationData(LogString.timeFinish);
                    }

                }
            }
        };

        mSerialMessageViewModel.onDistillFlag.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if(integer == 0){
                    //蒸馏完毕
                    mInstrumentStateViewModel.lightSwitchState.postValue(false);//灯灭
                    mInstrumentStateViewModel.valveSwitchState.postValue(false);//阀关闭
                    mInstrumentStateViewModel.heatSwitchState.postValue(false);//加热关闭
                    mInstrumentStateViewModel.refrigerationSwitchState.postValue(false);//制冷关闭
                }else{
                    //开始蒸馏
                    System.out.println("----------------------进入了蒸馏模式！-----------------------");
                    mInstrumentStateViewModel.lightSwitchState.postValue(true);
                    mInstrumentStateViewModel.valveSwitchState.postValue(true);
                    mInstrumentStateViewModel.heatSwitchState.postValue(true);
                    mInstrumentStateViewModel.refrigerationSwitchState.postValue(true);
                }
            }
        });

        initSwitchStateLog();
        initThread();

        //对串口接收到的数据进行处理
        mSerialMessageViewModel.serialBuffer.observe(this, new Observer<byte[]>() {
            @Override
            public void onChanged(byte[] bytes) {
                //称重与温度部分
                if(bytes[0]==0x55){
                    //System.out.println("接收到bytes，为：" + "weight:" + bytes[2] + bytes[3] + "temp:" + (int)bytes[4] + "+" + (int)bytes[5]);
                    double steamVolume = Protocol.handleWeight(bytes);
                    double temperature = Protocol.handleTemp(bytes);
                    mInstrumentStateViewModel.steamVolume.setValue((int)steamVolume);
                    mSerialMessageViewModel.curSteamVolume.postValue(steamVolume);
                    mInstrumentStateViewModel.temperature.setValue((int)temperature);
                    //System.out.println("得到温度和蒸馏量数据，温度值为：" + temperature + "   蒸馏量为：" + steamVolume);
                } else if(bytes[1] == 0x02){
                    //水位
                    if(bytes[3]==0x00){
                        mInstrumentStateViewModel.waterLevel.setValue(1);//水位值为1
                        mInstrumentStateViewModel.addWaterSwitchState.setValue(true);//加水设置为true
                        mInstrumentStateViewModel.toMaxMinWaterLevel.setValue(1);//水位下限
                        mInstrumentStateViewModel.securityDoorClosed.setValue(true);//安全门设置为true
                    }else  if(bytes[3]==0x01){
                        mInstrumentStateViewModel.waterLevel.setValue(6);//水位值为6
                        mInstrumentStateViewModel.securityDoorClosed.setValue(true);//安全门设置为true
                    }else if(bytes[3] == 0x03){
                        mInstrumentStateViewModel.toMaxMinWaterLevel.setValue(2);//水位上限
                        mInstrumentStateViewModel.addWaterSwitchState.setValue(false);//加水设置为false
                        mInstrumentStateViewModel.waterLevel.setValue(10);//水位值为10
                        mInstrumentStateViewModel.securityDoorClosed.setValue(true);//安全门设置为true
                    }else if(bytes[3] == 0x04){
                        mInstrumentStateViewModel.toMaxMinWaterLevel.setValue(1);//水位下限
                        mInstrumentStateViewModel.addWaterSwitchState.setValue(true);//加水设置为true
                        mInstrumentStateViewModel.waterLevel.setValue(1);//水位值为1
                        mInstrumentStateViewModel.securityDoorClosed.setValue(false);//安全门设置为false
                    }else if(bytes[5] == 0x05){
                        mInstrumentStateViewModel.waterLevel.setValue(6);//水位值为6
                        mInstrumentStateViewModel.securityDoorClosed.setValue(false);//安全门设置为false
                    }else if(bytes[5] == 0x07){
                        mInstrumentStateViewModel.toMaxMinWaterLevel.setValue(2);//水位上限
                        mInstrumentStateViewModel.addWaterSwitchState.setValue(false);//加水设置为false
                        mInstrumentStateViewModel.waterLevel.setValue(10);//水位值为10
                        mInstrumentStateViewModel.securityDoorClosed.setValue(false);//安全门设置为false
                    }
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        mSharedViewModel.setLogoutTime(df.format(new Date()));
        mDataBaseViewModel.dataBaseRepository.insertOperationLog(mSharedViewModel.operationLog.getValue());
    }

    @Override
    public void setTime(int time) {
        mInstrumentStateViewModel.targetTime.postValue(time);
        timeHandler.sendEmptyMessage(1);
    }

    public void initSwitchStateLog(){
//        mInstrumentStateViewModel.securityDoorClosed.observe(this, new Observer<Boolean>() {
//            @Override
//            public void onChanged(Boolean aBoolean) {
//                if(!aBoolean){
//                    mSharedViewModel.setOperationData(LogString.securityDoorOpen);
//                }else {
//                    mSharedViewModel.setOperationData(LogString.securityDoorClose);
//                }
//            }
//        });

        mInstrumentStateViewModel.heatSwitchState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mSharedViewModel.setOperationData(LogString.heatOn);
                    mSerialMessageViewModel.insertQueue(Protocol.heatTrue);
                }else {
                    mSharedViewModel.setOperationData(LogString.heatOff);
                    mSerialMessageViewModel.insertQueue(Protocol.heatFalse);
                }
            }
        });

        mInstrumentStateViewModel.valveSwitchState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mSharedViewModel.setOperationData(LogString.valveOn);
                    mSerialMessageViewModel.insertQueue(Protocol.valveTrue);
                }else {
                    mSharedViewModel.setOperationData(LogString.valveOff);
                    mSerialMessageViewModel.insertQueue(Protocol.valveFalse);
                }
            }
        });

        mInstrumentStateViewModel.addWaterSwitchState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mSharedViewModel.setOperationData(LogString.addWaterOn);
                    mSerialMessageViewModel.insertQueue(Protocol.addWaterTrue);
                }else {
                    mSharedViewModel.setOperationData(LogString.addWaterOff);
                    mSerialMessageViewModel.insertQueue(Protocol.addWaterFalse);
                }
            }
        });

        mInstrumentStateViewModel.lightSwitchState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mSharedViewModel.setOperationData(LogString.lightOn);
                    mSerialMessageViewModel.insertQueue(Protocol.lightTrue);
                }else {
                    mSharedViewModel.setOperationData(LogString.lightOff);
                    mSerialMessageViewModel.insertQueue(Protocol.lightFalse);
                }
            }
        });

        mInstrumentStateViewModel.refrigerationSwitchState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mSharedViewModel.setOperationData(LogString.coldOn);
                    mSerialMessageViewModel.insertQueue(Protocol.refrigerationTrue);
                }else {
                    mSharedViewModel.setOperationData(LogString.coldOff);
                    mSerialMessageViewModel.insertQueue(Protocol.refrigerationFalse);
                }
            }
        });


        mInstrumentStateViewModel.addCoolantSwitchState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mSharedViewModel.setOperationData(LogString.addCoolOn);
                    mSerialMessageViewModel.insertQueue(Protocol.addCoolantTrue);
                }else {
                    mSharedViewModel.setOperationData(LogString.addCoolOff);
                    mSerialMessageViewModel.insertQueue(Protocol.addCoolantFalse);
                }
            }
        });

        mInstrumentStateViewModel.sodaSwitchState.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mSharedViewModel.setOperationData(LogString.addSodaOn);
                    mSerialMessageViewModel.insertQueue(Protocol.sodaTrue);
                }else {
                    mSharedViewModel.setOperationData(LogString.addSodaOff);
                    mSerialMessageViewModel.insertQueue(Protocol.sodaFalse);
                }
            }
        });

    }

    public void initThread(){

        //串口发送数据
        sendHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 11) {
                    //从serialQueue中queue一个串口数据发送
                    Queue<byte[]> tempQueue = mSerialMessageViewModel.serialQueue.getValue();
                    if(!tempQueue.isEmpty()){
                        byte[] tempByte = tempQueue.poll();
                        mSerialMessageViewModel.serialQueue.postValue(tempQueue);
                        try {
                            SerialManager.getInstance().ttyS2Send(tempByte);
//                            System.out.println("send: "+ tempByte[0] + tempByte[1] + tempByte[2]
//                                    +tempByte[3] + tempByte[4]);
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.v("","");
                        }
                    }
                }
                super.handleMessage(msg);
            }
        };
        sendTimer = new Timer();
        sendTimerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = 11;
                sendHandler.sendMessage(message);
            }
        };
        sendTimer.schedule(sendTimerTask, 100, 200);

        //温度和蒸汽量
        steamAndTempHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 12) {
                    //向队列添加5505数据
                    mSerialMessageViewModel.insertQueue(Protocol.weight);
                }
                super.handleMessage(msg);
            }
        };
        steamAndTempTimer = new Timer();
        steamAndTempTimerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = 12;
                steamAndTempHandler.sendMessage(message);
            }
        };
        steamAndTempTimer.schedule(steamAndTempTimerTask, 200, 1000);

        //水位值FE02,1s一次
        waterLevelHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what == 13){
                    //向队列添加FE02数据
                    mSerialMessageViewModel.insertQueue(Protocol.waterLevel);
                }
                super.handleMessage(msg);
            }
        };
        Timer waterLevelTimer = new Timer();
        TimerTask waterLevelTimerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = 13;
                waterLevelHandler.sendMessage(message);
            }
        };
        waterLevelTimer.schedule(waterLevelTimerTask, 500, 1000);

        //接收线程
        recieveThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    byte[] recieveByte = new byte[100];
                    try {
                        SerialManager.getInstance().ttyS2Recieve(recieveByte);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mSerialMessageViewModel.serialBuffer.postValue(recieveByte);
                }
            }
        });
        recieveThread.start();
    }


}
